import Vue from 'vue'

const state = {
  shopInfo: {
    latitude: '',
    longitude: '',
    name: '',
    address: '',
    phone: '',
    qrcode: '',
    businessHours: '',
    shopAcronym: ''
  },
  loading: false,
  loaded: false
}

const mutations = {
  SET_SHOP_INFO(state, data) {
    state.shopInfo = data
    state.loaded = true
  },
  SET_LOADING(state, status) {
    state.loading = status
  }
}

const actions = {
  async getShopInfo({ commit, state }) {
    // 如果数据已加载且存在，直接返回
    if (state.loaded && state.shopInfo.shopAcronym) {
      return state.shopInfo
    }
    
    // 如果正在加载，避免重复请求
    if (state.loading) {
      return
    }
    
    try {
      commit('SET_LOADING', true)
      const response = await Vue.prototype.$get('home/about')
      commit('SET_SHOP_INFO', response.data)
      return response.data
    } catch (error) {
      console.error('获取店铺信息失败:', error)
      // 请求失败时也标记loaded，避免反复请求
      commit('SET_LOADED', true)
      return state.shopInfo
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 强制刷新店铺信息的方法
  async refreshShopInfo({ commit }) {
    try {
      commit('SET_LOADING', true)
      const response = await Vue.prototype.$get('home/about')
      commit('SET_SHOP_INFO', response.data)
      return response.data
    } catch (error) {
      console.error('刷新店铺信息失败:', error)
      return null
    } finally {
      commit('SET_LOADING', false)
    }
  }
}

const getters = {
  shopInfo: state => state.shopInfo,
  shopLoading: state => state.loading,
  shopLoaded: state => state.loaded
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
